<template>
    <page-layout>
        <template v-slot:header>
            <el-button size="small" type='primary' @click="saveEvt">保存</el-button>
            <el-button size="small">返回</el-button>
        </template>
        <el-form :model="page"
            :rules="rules"
            ref="ruleForm"
            size="small"
            label-width="100px">
            <!-- prop属性是给rules使用的，表示使用rules中的name属性进行数据校验 -->
            <el-row>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产品名字" prop="name">
                        <el-input v-model="page.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产品状态" prop="state">
                        <el-input value='新建' readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="成本价" prop="pure_price">
                        <el-input v-model="page.pure_price" type='number'></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="定价" prop="price">
                        <el-input v-model="page.price" type='number'></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="优惠" prop="discount">
                        <el-input v-model="page.discount" type='number'></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="限购" prop="limit">
                        <el-input v-model="page.limit" type='number'></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="上架时间" prop="sale_stime">
                        <el-date-picker v-model="page.sale_stime"
                            type="date"
                            placeholder="选择上架日期"/>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="下架时间" prop="sale_etime">
                        <el-date-picker v-model="page.sale_etime"
                            type="date"
                            placeholder="选择下架日期"/>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="page.type" placeholder="请选择">
                            <el-option v-for="item in options.type"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="单位" prop="unit">
                        <el-select v-model="page.unit" placeholder="请选择">
                            <el-option v-for="item in options.unit"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="品级" prop="level">
                        <el-select v-model="page.level" placeholder="请选择">
                            <el-option v-for="item in options.level"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="产地" prop="place">
                        <el-input v-model="page.place"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="品牌" prop="brand">
                        <el-input v-model="page.brand"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="详情" prop="detail">
                        <el-tag style="margin: 0 10px 10px 0;"
                            v-for="tag in page.detail"
                            :key="tag"
                            @close="closeEvt(tag, 'detail')"
                            closable>
                            {{tag}}
                        </el-tag>
                        <el-button size="small" @click="filePickEvt('detail')" icon='el-icon-upload2'/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="banner" prop="banner">
                        <el-tag style="margin: 0 10px 10px 0;"
                            v-for="tag in page.banner"
                            :key="tag"
                            @close="closeEvt(tag, 'banner')"
                            closable>
                            {{tag}}
                        </el-tag>
                        <el-button size="small" @click="filePickEvt('banner')" icon='el-icon-upload2'/>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="page.remark"></el-input>
                    </el-form-item>
                </el-col>
                <MyList v-model="page.list"/>
            </el-row>
        </el-form>
    </page-layout>
</template>

<script>
import { dictListApi, fileUploadApi, productSaveApi } from '@/apis/productApi'
import { filePicker } from '@/utils'
import MyList from './MyList.vue'
export default {
    components: { MyList },
    data() {
        return {
            page: {
                "list": [],
                "name": "",
                "state": "new",
                "pure_price": 0,
                "price": 0,
                "discount": 0,
                "limit": 0,
                "sale_stime": "",
                "sale_etime": "",
                "type": "",
                "unit": "",
                "level": "",
                "place": "",
                "brand": "",
                "detail": [],
                "banner": [],
                "remark": ""
            },
            rules: {
                // name属性用于在表单项的prop属性上，可能存在多个校验，所以是数组
                name: [
                    {required: true, message: '产品名字必须输入'}
                ],
                pure_price: [
                    {required: true, message: '成本价必须输入'},
                    {
                        validator: (_, value, callback) => {
                            if (value * 1 >= this.page.price * 1) {
                                callback(new Error('成本价不能高于定价'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                price: [
                    {required: true, message: '定价必须输入'},
                    {
                        validator: (_, value, callback) => {
                            if (value * 1 <= this.page.pure_price * 1) {
                                callback(new Error('定价不能低于成本价'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                sale_stime: [
                    {required: true, message: '必须指定上架时间'},
                    {
                        validator: (_, val, cb) => {
                            if (val.getTime() < (Date.now() - (24 * 60 * 60 * 1000))) {
                                cb(new Error('上架时间不能比今天早'))
                            } else if ((new Date(this.page.sale_etime).getTime()) < (val.getTime() + (24 * 60 * 60 * 1000))) {
                                cb(new Error('上架时间不能晚于下架时间'))
                            } else {
                                cb()
                            }
                        }
                    }
                ],
                sale_etime: [
                    {required: true, message: '必须指定下架时间'},
                    {
                        validator: (_, val, cb) => {
                            if (val.getTime() < ((new Date(this.page.sale_stime).getTime()) + (24 * 60 * 60 * 1000))) {
                                cb(new Error('下架时间不能早于上架时间'))
                            } else {
                                cb()
                            }
                        }
                    }
                ],
                discount: [
                    {required: true, message: '优惠价格必须数据'}
                ],
                limit: [
                    {required: true, message: '限购数量必须输入'}
                ],
                type: [
                    {required: true, message: '类型必须输入'}
                ],
                unit: [
                    {required: true, message: '单位必须输入'}
                ],
                level: [
                    {required: true, message: '品级必须输入'}
                ],
                place: [
                    {required: true, message: '产地必须输入'}
                ],
                brand: [
                    {required: true, message: '品牌必须输入'}
                ]
            },
            options: {
                level: [],
                unit: [],
                type: []
            }
        }
    },
    mounted() {
        Promise.all([
            dictListApi('UNITS'),
            dictListApi('MEDICAL'),
            dictListApi('PRODUCT_LEVEL')
        ]).then(([unit, type, level]) => {
            if (unit.code === 200) this.options.unit = unit.data.rows
            if (type.code === 200) this.options.type = type.data.rows
            if (level.code === 200) this.options.level = level.data.rows
        })
    },

    methods: {
        saveEvt() {
            let msg = ''
            for (let i = 0;i < this.page.list.length;i ++) {
                let item = this.page.list[i]
                if (item.count <= 0) {
                    msg = `第【${i + 1}】行的数量没有填写`
                    break
                }
                if (!item.supplier_name) {
                    msg = `第【${i + 1}】行的供应商名字没有填写`
                    break
                }
            }
            if (!!msg) {
                this.$message.error(msg)
                return
            }

            this.$refs.ruleForm.validate().then(() => {
                
                productSaveApi({
                    ...this.page,
                    banner: this.page.banner.join('--'),
                    detail: this.page.detail.join('--')
                }).then(d => {
                    console.log(d)
                })
            }).catch(() => {
                console.log('---------------------- 校验失败')
            })
        },
        filePickEvt(type) {
            filePicker(files => {
                // 这里的上传要使用FormData对象
                // 它是W3C定义的一个用于把数据对象转为form表单对象的一个方法(js对象序列化为Form对象)
                let formData = new FormData()
                // 因为files是一个伪数组
                Array(files.length).fill().forEach((_, i) => {
                    // 循环添加文件数据到formData对象中
                    formData.append('file', files[i])
                })
                // 调用接口
                fileUploadApi('product_' + type, formData).then(d => {
                    if (d.code === 200) {
                        this.page[type] = this.page[type].concat(
                            d.data.map(it => it.path)
                        )
                    }
                })
            })
        },
        closeEvt(tag, type) {
            // this.page.detail = this.page.detail.filter(it => it !== tag)
            this.page[type].splice(this.page[type].findIndex(it => it === tag), 1)
        }
    }
}
</script>